package cn.gift.exception.handler;

import cn.gift.exception.BusinessException;
import cn.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description:
 * 全局异常处理类  执行Controller后
 * @date: 2023/4/25 15:22
 * @author: ZhaoLc
 * @version: 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 相当于 catch
     * @return AjaxResult
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException businessException){
        businessException.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(businessException.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception exception){
        exception.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,请稍后重试!");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException me){
        me.printStackTrace();
        BindingResult bindingResult = me.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        return AjaxResult.me().setSuccess(false).setMessage(msg);
    }
}
